package com.leyou.order.listen;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.leyou.order.data.entity.OrderGoods;
import com.leyou.order.data.entity.OrderGoodsItem;
import com.leyou.order.service.OrderGoodsItemService;
import com.leyou.order.service.OrderGoodsService;
import com.leyou.rabbitmq.OrderRabbitMq;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * @author xhh
 * @describe 描述
 * @date 2022/7/28 19:57
 * @ClassName OrderListen
 */
@Configuration
public class OrderListen {
    @Autowired
    private OrderGoodsService orderGoodsService;
    @Autowired
    private OrderGoodsItemService orderGoodsItemService;
    @RabbitHandler
    @RabbitListener(queues = OrderRabbitMq.ORDER_DEAD_QUEUE)
    public void OrderListen(String number, Message message, Channel channel){
        try {
            System.err.println("过期了 检查有没有支付");
            System.err.println("order_number:"+number);


            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("number",number);

            OrderGoods one = orderGoodsService.getOne(queryWrapper);
            //1-已支付,2-未支付,3-已超时,4-已取消
            if(one.getState()==2){
                one.setState(3);
                boolean update = orderGoodsService.update(one, queryWrapper);
                if(update){
                    queryWrapper.clear();
                    queryWrapper.eq("father_number",number);
                    OrderGoodsItem item=new OrderGoodsItem();
                    item.setState(-2);
                    orderGoodsItemService.update(item, queryWrapper);
                }
                
            }else if(one.getState()==1){
                boolean update = orderGoodsService.update(one, queryWrapper);
            }else{

            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

        } catch (Exception e) {
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }
}
